require "csv"

class EventCsvParser
  
public
  # seminorParams = [{:name => "ルームA 13:00〜", :colNum => 5}, {:name => "", :colNum => 6}]
  # pickparams = {:name => 1, :mail => 2, :number => 3}
  def parseEventAndSeminor(csvString, eventName, seminorParams, pickParams)
    event = Event.new(:name => eventName).save

    # セミナー登録
    seminorParams.each do |param|
      event.seminors.create(:name => param[:name])
    end
    seminors = event.seminors.find(:all)
    
    parseCsv(csvString, pickParams) do |csv, row, name, mail, number, user_hash|
      event.visitors.create(:csv => csv, :name => name, :mail => mail, :number => number, :user_hash => user_hash)
      
      seminors.each do |seminor|
        # ToDo:セミナーの参加条件を確認して、登録
        
      end
    end
    
  end
  
  # pickparams = {:name => 1, :mail => 2, :number => 3}
  def parseEvent(csvString, eventName, pickParams)
    event = Event.new(:name => eventName).save
    
    parseCsv(csvString, pickParams) do |csv, row, name, mail, number, user_hash|
      event.visitors.create(:csv => csv, :name => name, :mail => mail, :number => number, :user_hash => user_hash)
    end
  end
  
private

  def parseCsv(csvString, pickParams)
    csv = CSV::stringReader.new(csvString)
    csvLines = []
    csv.each_line do |line|
      csvLines << line
    end
    
    header = csv.shift
    i = 0
    csv.each do |row|
      i += 1
      name = ""
      mail = ""
      number = ""
      pickParams.each do |key, colNum|
        case key
        when :name then name = row[colNum]
        when :mail then mail = row[colNum]
        when :number then number = row[colNum]
        end
      end
      user_hash = MD5.md5(csvLines[i])
      yeild(csvLines[i], row, name, mail, number, user_hash)
    end
  end

end

